package com.yes_iot.controller;

import com.yes_iot.entity.VisualDisplay;
import com.yes_iot.entity.VisualMoudle;
import com.yes_iot.entity.VisualMoudleLibrary;
import com.yes_iot.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/yesiot")
@Slf4j
@CrossOrigin
public class VisualDisplayController extends BaseController{

    @RequestMapping(value = "/visual/display/save", method = RequestMethod.POST)
    public Result save(@RequestBody VisualDisplay info)  {
        try {
            List<VisualDisplay> devId = visualDisplayService.findByDevId(info.getDevCode());
            if (devId!=null&&devId.size()>0&&info.getParentId()==null){
                return Result.failed("设备已创建组态");
            }
            if (info.getId()==null){
                UUID uuid = UUID.randomUUID();
                info.setId(uuid);
                info.setKeycode(UUID.randomUUID().toString().replace("-", ""));
                info.setCreatedTime(System.currentTimeMillis());
                info.setSceneId(null);
                if ("1".equals(info.getModel())){
                    String devCode = info.getDevCode();
                    info.setDevModelId(devCode.substring(5,10));
                }
            }
            VisualDisplay visualDisplay = visualDisplayService.save(info);
            return Result.succeed(visualDisplay,"查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }
    @RequestMapping(value = "/visual/display/update", method = RequestMethod.PUT)
    public Result update(@RequestBody VisualDisplay obj)   {
        try {
            if (StringUtils.isNotEmpty( obj.getKeycode())) {
                visualDisplayService.updateByKeycode(obj);
            }
            return Result.succeed("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }
    @RequestMapping(value = "/visual/display/update/name/seq", method = RequestMethod.PUT)
    public Result updateNameAndSeq(@RequestBody VisualDisplay obj)   {
        try {
            if (StringUtils.isNotEmpty( obj.getKeycode())) {
                visualDisplayService.updateNameAndSeqByKeycode(obj);
            }
            return Result.succeed("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }
    @RequestMapping(value = "/visual/display/delete/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id )   {
        try {
            visualDisplayService.delete(UUID.fromString(id));
            return Result.succeed("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }
    @RequestMapping(value = "/visual/display/list/dev/id/{devCode}",method = RequestMethod.GET)
    public Result findByDevId(@PathVariable String devCode ){
        try {
            List<VisualDisplay> visualDisplays=visualDisplayService.findByDevId(devCode);

            return Result.succeed(visualDisplays,"查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed("查询失败");
        }
    }
    @RequestMapping(value = "/visual/display/list/farmId/{farmId}",method = RequestMethod.GET)
    public Result findByFarmId(@PathVariable String farmId ){
        try {
            List<VisualDisplay> visualDisplays=visualDisplayService.findByFarmId(farmId);

            return Result.succeed(visualDisplays,"查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed("查询失败");
        }
    }
    @RequestMapping(value = "/visual/display", method = RequestMethod.GET)
    public VisualDisplay selectOne(@RequestParam(required = false) String keycode)  {
        try {
            return visualDisplayService.findByKeyCode(keycode);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @RequestMapping(value = "/visual/display/sub/all", method = RequestMethod.GET)
    public List<VisualDisplay> selectList(@RequestParam String id)  {
        try {
            return visualDisplayService.findByParentIdOrId(UUID.fromString(id));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @RequestMapping(value = "/visual/display/list/dev/model/id/{devModelId}",method = RequestMethod.GET)
    public Result findByDevModelId(@PathVariable String devModelId ){
        try {
            List<VisualDisplay> visualDisplays=visualDisplayService.findByDevModelId(devModelId);

            return Result.succeed(visualDisplays,"查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed("查询失败");
        }
    }

    @RequestMapping(value = "/visual/display/applyModelVisual",method = RequestMethod.GET)
    public Result applyModelVisual(@RequestParam String keyCode, @RequestParam String apply){
        try {
            HashMap<String, String> keyCodeMap = new HashMap<>();

            VisualDisplay visualDisplayApply=visualDisplayService.findByKeyCode(apply);
            VisualDisplay visualDisplay = visualDisplayService.findByKeyCode(keyCode);
            if (visualDisplayApply!=null){
                visualDisplay.setContent(visualDisplayApply.getContent());
                visualDisplay.setConfig(visualDisplayApply.getConfig());
                visualDisplay.setModel(visualDisplayApply.getModel());
            }
            keyCodeMap.put(visualDisplayApply.getKeycode(),visualDisplay.getKeycode());
            visualDisplay = visualDisplayService.save(visualDisplay);
            visualDisplayService.deleteByParentId(visualDisplay.getId());
            List<VisualMoudleLibrary> visualMoudleLibraries = visualMoudleLibraryService.findVisualMoudelLibraryByVisualDisplayParentId(visualDisplayApply.getId().toString());
            if (visualMoudleLibraries!=null&& visualMoudleLibraries.size()>0){
                for (VisualMoudleLibrary visualMoudleLibrary:visualMoudleLibraries) {
                    VisualMoudleLibrary moudleLibrary = new VisualMoudleLibrary();
                    moudleLibrary.setId(UUID.randomUUID());
                    moudleLibrary.setCreatedTime(System.currentTimeMillis());
                    moudleLibrary.setSeq(visualMoudleLibrary.getSeq());
                    moudleLibrary.setName(visualMoudleLibrary.getName());
                    moudleLibrary.setVisualDisplayParentId(visualDisplay.getId());
                    VisualMoudleLibrary save = visualMoudleLibraryService.save(moudleLibrary);
                    List<VisualMoudle> visualMoudles=visualMoudleService.findByVisualMoudleLibraryId(visualMoudleLibrary.getId());
                    if (visualMoudles!=null && visualMoudles.size()>0){
                        for (VisualMoudle visualMoudle:visualMoudles) {
                            VisualMoudle visualMoudleNew= new VisualMoudle();
                            visualMoudleNew.setId(UUID.randomUUID());
                            visualMoudleNew.setCreatedTime(System.currentTimeMillis());
                            visualMoudleNew.setName(visualMoudle.getName());
                            visualMoudleNew.setDisImg(visualMoudle.getDisImg());
                            visualMoudleNew.setMoudleType(visualMoudle.getMoudleType());
                            visualMoudleNew.setVisualMoudleLibraryId(save.getId());
                            visualMoudleService.save(visualMoudleNew);
                        }
                    }
                }
            }

            List<VisualDisplay> visualDisplays = visualDisplayService.findByParentId(visualDisplayApply.getId());
            if (visualDisplays!=null && visualDisplays.size()>0){
                for (VisualDisplay display:visualDisplays) {
                    VisualDisplay newDisplay = new VisualDisplay();
                    UUID uuid = UUID.randomUUID();
                    newDisplay.setId(uuid);
                    newDisplay.setKeycode(UUID.randomUUID().toString().replace("-", ""));
                    newDisplay.setCreatedTime(System.currentTimeMillis());
                    newDisplay.setParentId(visualDisplay.getId());
                    newDisplay.setModel(display.getModel());
                    newDisplay.setName(display.getName());
                    newDisplay.setContent(display.getContent());
                    newDisplay.setConfig(display.getConfig());
                    newDisplay.setSeq(display.getSeq());
                    newDisplay.setDisType(display.getDisType());
                    newDisplay.setDevCode(visualDisplay.getDevCode());
                    newDisplay.setIsMould(false);
                    newDisplay.setFarmId(display.getFarmId());
                    newDisplay.setGreenHouseId(display.getGreenHouseId());
                    newDisplay.setDevModelId(display.getDevModelId());
                    VisualDisplay save = visualDisplayService.save(newDisplay);
                    keyCodeMap.put(display.getKeycode(),save.getKeycode());
                }
            }

            if (keyCodeMap.size()>0){
                for (Map.Entry<String,String> entry:keyCodeMap.entrySet()) {
                    VisualDisplay byKeyCode = visualDisplayService.findByKeyCode(entry.getValue());
                    if (StringUtils.isNotEmpty(byKeyCode.getContent())){
                        Document doc = Jsoup.parse(byKeyCode.getContent());
                        Elements select = doc.select("div[nid='0'][jty='3']");
                        for (int i = 0; i < select.size(); i++) {
                            String code = select.get(i).attr("code");
                            String s = keyCodeMap.get(code);
                            select.get(i).attr("code",s);
                            select.get(i).attr("jurl","./show.html?keyCode="+s);
                        }
                        Elements select1 = doc.select("div[nid='0'][jty='1']");
                        for (int i = 0; i < select1.size(); i++) {
                            String code = select1.get(i).attr("code");
                            String s = keyCodeMap.get(code);
                            select1.get(i).attr("code",s);
                            select1.get(i).attr("jurl","./show.html?keyCode="+s);
                        }
                        String string = doc.toString();
                        byKeyCode.setContent(string);
                        visualDisplayService.save(byKeyCode);
                    }
                }
            }
            return Result.succeed("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed(e.getMessage(),"查询失败");
        }
    }
    @RequestMapping(value = "/visual/display/bool/dev/code/{devCode}",method = RequestMethod.GET)
    public Result findByDevCode(@PathVariable String devCode){
        try {
            List<VisualDisplay> displayList = visualDisplayService.findByDevId(devCode);
            if (displayList!=null&&displayList.size()>0){
                return Result.succeed("查询成功");
            }else{
                return Result.failed("查询失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.failed("查询失败");
        }
    }
    @RequestMapping(value = "/visual/display/dev/code/list",method = RequestMethod.POST)
    public Result findByDevCodeList(@RequestBody Map<String,Object> map){
        List<VisualDisplay> displayList = null;
        try {
            Object devCodeListObj=map.get("devCodeList");
            if (ObjectUtils.isEmpty(devCodeListObj)){
                throw new NullPointerException();
            }
            List<String>  devCodeList = (List<String>) devCodeListObj;
            displayList=visualDisplayService.findByDevCodeList(devCodeList);
            return Result.succeed(displayList,"查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed(displayList,"查询失败");
        }
    }
    @RequestMapping(value = "/visual/display/farmId/list",method = RequestMethod.POST)
    public Result findByFarmIdList(@RequestBody Map<String,Object> map){
        List<VisualDisplay> displayList = null;
        try {
            Object farmIdListObj=map.get("farmIdList");
            if (ObjectUtils.isEmpty(farmIdListObj)){
                throw new NullPointerException();
            }
            List<Integer>  farmIdList = (List<Integer>) farmIdListObj;
            displayList=visualDisplayService.findByFarmIdList(farmIdList);
            return Result.succeed(displayList,"查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed(displayList,"查询失败");
        }
    }

    @RequestMapping(value = "/visual/display/login/{keyCode}", method = RequestMethod.GET)
    public Result findLoginByKeyCode(@PathVariable String keyCode ){
        try {
            String fatherKeyCode="";
            VisualDisplay display = visualDisplayService.findByKeyCode(keyCode);
            if (display!=null){
                UUID parentId = display.getParentId();
                if (parentId!=null){
                    VisualDisplay father =visualDisplayService.findById(parentId);
                    fatherKeyCode=father.getKeycode();
                }else{
                    fatherKeyCode= keyCode;
                }
            }

            Map<String,Object> login=visualDisplayService.findLoginByKeyCode(fatherKeyCode);

            return Result.succeed(login,"成功");
        } catch (Exception e) {
            e.getMessage();
            return Result.failed(e.getMessage());
        }
    }
}
